package com.shiwaixiangcun.customer.module.heath

import android.annotation.SuppressLint
import android.os.Bundle
import android.support.constraint.ConstraintLayout
import android.util.Log
import android.view.View
import com.google.gson.reflect.TypeToken
import com.lzy.okgo.OkGo
import com.lzy.okgo.callback.StringCallback
import com.lzy.okgo.model.Response
import com.shiwaixiangcun.customer.ConfigSps
import com.shiwaixiangcun.customer.GlobalApi
import com.shiwaixiangcun.customer.R
import com.shiwaixiangcun.customer.event.EventUtil
import com.shiwaixiangcun.customer.event.SimpleEvent
import com.shiwaixiangcun.customer.network.ResponseConfig
import com.shiwaixiangcun.customer.ui.fragment.LazyFragment
import com.shiwaixiangcun.customer.utils.*
import kotlinx.android.synthetic.main.layout_fragment_data.*
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * Author   Administrator
 * Date     2018/1/22
 * Desc     健康数据
 *
 * @author Administrator
 */

class FragmentData : LazyFragment(), View.OnClickListener {

    companion object {
        val BUG_TAG = "fragmentData"
        val REQUEST_DATA = 0x1001
        val CHANGE_TAB = 0x1010
        fun newInstance(userID: Long?): FragmentData {
            val f = FragmentData()
            val args = Bundle()
            args.putLong("userID", userID!!)
            f.arguments = args
            return f

        }
    }

    private var strToken: String? = null
    private var userID: Long? = null
    private var refreshToken: String? = null
    override fun getContentViewLayoutID(): Int {
        return R.layout.layout_fragment_data
    }

    override fun initViewsAndEvents(view: View) {
        initClickListener()
        strToken = AppSharePreferenceMgr.get(activity?.applicationContext, ConfigSps.CURRENT_TOKEN, "") as String
        refreshToken = AppSharePreferenceMgr.get(activity, ConfigSps.CURRENT_REFRESH_TOKEN, "") as String


    }


    /**
     * 获取健康数据
     */
    private fun initData(id: Long?) {
        if (id == 0L) {
            return
        }
        id?.let {
            OkGo.get<String>(GlobalApi.userHealthData)
                    .params("access_token", strToken)
                    .params("customerId", it)
                    .execute(object : StringCallback() {
                        override fun onSuccess(response: Response<String>?) {
                            val type = object : TypeToken<CommonEntity<HealthData>>() {}.type
                            val commonListEntity = JsonUtil.fromJson<CommonEntity<HealthData>>(response?.body(), type)

                            when (commonListEntity.responseCode) {
                                ResponseConfig.SUCCESS -> {
                                    EventUtil.getInstance().post(SimpleEvent(SimpleEvent.HEALTH_DATA, REQUEST_DATA, commonListEntity.data))
                                }
                                ResponseConfig.TOKEN_INVALID -> {
                                    showToast("当前登录失效")
                                    RefreshTokenUtil.refreshToken(mContext, refreshToken)
                                }
                            }
                        }

                    })
        }
    }


    override fun onFirstUserVisible() {

        userID?.let { initData(it) }
    }

    override fun onUserVisible() {
        initData(userID)
    }

    override fun onUserInvisible() {
    }

    override fun destroyViewAndThing() {
        EventUtil.getInstance().unregister(this)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun updateUI(simpleEvent: SimpleEvent) {
        when (simpleEvent.mEventType) {
            SimpleEvent.HEALTH_DATA -> {
                when (simpleEvent.mEventValue) {
                //获取数据更新界面
                    REQUEST_DATA -> {
                        val data = simpleEvent.data as HealthData
                        loadDataToUi(data)
                    }

                }
            }
            SimpleEvent.HEALTH_CHANGE_FAMILY -> {
                when (simpleEvent.mEventValue) {
                    CHANGE_TAB -> {
                        val id = simpleEvent.data as Long
                        this.userID = id
                        if (this.isUserVisiable) {
                            Log.e(BUG_TAG, "change")
                            initData(userID!!)
                        }
                    }
                }
            }
        }

    }

    /**
     * 更新界面
     *
     */
    @SuppressLint("SetTextI18n")
    private fun loadDataToUi(data: HealthData) {

//        用户15892547304 的数据出现异常 所以删除了BloodCreateTim==0的判断
//        暂时不清楚以前的需求是什么  2018/3/15
//        if (data == null || data.bloodCreateTime == 0L) {
        if (data == null) {
            layout_data.visibility = View.GONE
            layout_empty.visibility = View.VISIBLE
        } else {
            layout_empty.visibility = View.GONE
            layout_data.visibility = View.VISIBLE
            //设置心率
            tv_p_data.text = "${data.heartRate}"
            tv_p_date.text = DateUtil.getTimeFormatString(data.heartRateTime)
            setVisible(data.heartRateStatus, layout_hr)

            //设置血压
            tv_bp_data.text = "${data.shrinkBlood}/${data.relaxationBlood}"
            tv_bp_date.text = DateUtil.getTimeFormatString(data.pressureCreateTime)
            setVisible(data.pressureStatus, layout_bp)

            //设置血糖

            tv_glu_data.text = "${data.bloodSugar}"
            tv_glu_date.text = DateUtil.getTimeFormatString(data.sugarCreateTime)
            setVisible(data.sugarStatus, layout_fbg)
            //设置体重
            tv_bw_data.text = "${data.weight}"
            tv_bw_date.text = DateUtil.getTimeFormatString(data.bmiCreateTime)
            tv_bw_other.text = "BMI ${data.bmi}"
            setVisible(data.bmiStatus, layout_bw)

            //设置血脂四项

            tv_tcho_data.text = "${data.totalCholesterol}"
            tv_hdl_data.text = "${data.topLipo}"
            tv_ldl_data.text = "${data.lowLipo}"
            tv_tg_data.text = "${data.triglyceride}"
            tv_tc_date.text = DateUtil.getTimeFormatString(data.bloodCreateTime)
            setVisible(data.bloodStatus, layout_tc)
        }
    }


    private fun initClickListener() {
        layout_bp.setOnClickListener(this)
        layout_bw.setOnClickListener(this)
        layout_fbg.setOnClickListener(this)
        layout_hr.setOnClickListener(this)
        layout_tc.setOnClickListener(this)
    }


    /**
     * 设置控件颜色以及是否可见
     *
     * @param status 状态
     * @param view   需要判定的布局
     */
    private fun setVisible(status: String, view: ConstraintLayout) {
        if (StringUtil.isEmpty(status)) {
            view.visibility = View.GONE
            return
        }
        when (status) {
            "DANGER" -> view.background = resources.getDrawable(R.drawable.shape_red_corner_gradient)
            "NORMAL" -> view.background = resources.getDrawable(R.drawable.shape_green_corner_gradient)
            "WARNING" -> view.background = resources.getDrawable(R.drawable.shape_yellow_corner_gradient)
            else -> {
                view.background = resources.getDrawable(R.drawable.shape_green_corner_gradient)
            }
        }
    }


    override fun onClick(view: View) {
        val bundle = Bundle()
        userID?.let { bundle.putLong("customID", it) }
        when (view.id) {
        //跳转至血压详情
            R.id.layout_bp -> {
                readyGo(BloodPressureActivity::class.java, bundle)
            }
        //跳转至体重详情
            R.id.layout_bw -> {
                readyGo(WeightActivity::class.java, bundle)
            }
        //跳转至空腹血糖
            R.id.layout_fbg -> {
                readyGo(BloodSugarActivity::class.java, bundle)
            }
        //跳转至心率详情
            R.id.layout_hr -> {
                readyGo(HeartRateActivity::class.java, bundle)
            }
        //跳转至血脂四项
            R.id.layout_tc -> {
                readyGo(BloodFatActivity::class.java, bundle)
            }

        }

    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        EventUtil.getInstance().register(this)
        val bundle = arguments

        if (bundle != null) {
            userID = bundle.getLong("userID")
        }
    }

}
